import { useState, useRef, useEffect } from "react";
import { BORDER_COLOR } from "~/constants";
import SettingsIcon from "~/components/icons/SettingsIcon";

interface Props {
  children: React.ReactNode;
  onSettingsClick?: () => void;
}

interface Position {
  x: number;
  y: number;
}

export default function FloatingToolBar({ children, onSettingsClick }: Props) {
  const toolbarRef = useRef<HTMLDivElement>(null);
  const [isExpanded, setIsExpanded] = useState(true);
  const [position, setPosition] = useState<Position>(() => {
    // 尝试从localStorage获取上次保存的位置
    const savedPosition = localStorage.getItem('floatingToolbarPosition');
    if (savedPosition) {
      try {
        const parsed = JSON.parse(savedPosition);
        // 确保x坐标始终靠近右侧边缘
        if (toolbarRef.current) {
          parsed.x = window.innerWidth - toolbarRef.current.offsetWidth;
        } else {
          // 估算工具栏宽度
          parsed.x = window.innerWidth;
        }
        return parsed;
      } catch (e) {
        // 解析失败则使用默认位置
      }
    }
    
    // 默认位置：屏幕右侧边缘
    return { 
      x: window.innerWidth ,
      y: (window.innerHeight / 2) + (window.innerHeight / 4) - 100
    };
  });
  const [dragging, setDragging] = useState(false);
  const [dragStart, setDragStart] = useState({ x: 0, y: 0 });

  // 精确设置位置（在组件挂载后，当能获取到真实尺寸时）
  useEffect(() => {
    if (toolbarRef.current) {
      const toolbar = toolbarRef.current;
      // 确保工具栏始终靠近右侧边缘
      const x = window.innerWidth - toolbar.offsetWidth;
      let y = position.y;
      
      // 确保工具栏不会完全超出屏幕边界
      y = Math.max(20, Math.min(window.innerHeight - toolbar.offsetHeight - 20, y));
      
      setPosition({ x, y });
    }
  }, []);

  // 保存位置到localStorage（只保存y坐标，x坐标始终自动靠右）
  useEffect(() => {
    if (position) {
      // 只保存y坐标，因为x坐标始终自动计算
      const positionToSave = { x: 'auto', y: position.y };
      localStorage.setItem('floatingToolbarPosition', JSON.stringify(positionToSave));
    }
  }, [position]);

  // 监听窗口大小变化，确保工具栏始终靠右
  useEffect(() => {
    const handleResize = () => {
      if (toolbarRef.current) {
        const toolbar = toolbarRef.current;
        const x = window.innerWidth - toolbar.offsetWidth - 20;
        setPosition((prev: Position) => ({ ...prev, x }));
      }
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  const handleMouseDown = (e: React.MouseEvent) => {
    setDragging(true);
    setDragStart({
      x: e.clientX - position.x,
      y: e.clientY - position.y
    });
  };

  const handleTouchStart = (e: React.TouchEvent) => {
    const touch = e.touches[0];
    setDragging(true);
    setDragStart({
      x: touch.clientX - position.x,
      y: touch.clientY - position.y
    });
  };

  const handleMouseMove = (e: MouseEvent) => {
    if (dragging) {
      const newY = e.clientY - dragStart.y;
      
      setPosition((prev: Position) => ({
        x: prev.x, // x坐标保持不变，始终靠右
        y: newY
      }));
    }
  };

  const handleTouchMove = (e: TouchEvent) => {
    if (dragging) {
      const touch = e.touches[0];
      const newY = touch.clientY - dragStart.y;
      
      setPosition((prev: Position) => ({
        x: prev.x, // x坐标保持不变，始终靠右
        y: newY
      }));
    }
  };

  const handleMouseUp = () => {
    setDragging(false);
  };

  // 添加事件监听器
  useEffect(() => {
    if (dragging) {
      window.addEventListener('mousemove', handleMouseMove);
      window.addEventListener('touchmove', handleTouchMove, { passive: false });
      window.addEventListener('mouseup', handleMouseUp);
      window.addEventListener('touchend', handleMouseUp);
    }

    return () => {
      window.removeEventListener('mousemove', handleMouseMove);
      window.removeEventListener('touchmove', handleTouchMove);
      window.removeEventListener('mouseup', handleMouseUp);
      window.removeEventListener('touchend', handleMouseUp);
    };
  }, [dragging]);

  const toggleExpanded = () => {
    setIsExpanded(!isExpanded);
  };

  return (
    <div
      ref={toolbarRef}
      style={{
        position: "fixed",
        left: position.x,
        top: position.y,
        zIndex: 1000,
        display: "flex",
        flexDirection: "column-reverse",
        alignItems: "center",
        backgroundColor: "rgba(24, 24, 33, 0.7)",
        border: "1px solid " + BORDER_COLOR,
        borderRadius: "25px",
        padding: "2px",
        transition: "all 0.3s ease",
        cursor: dragging ? "grabbing" : "grab",
        minWidth: isExpanded ? "auto" : "40px",
        transform: dragging ? "scale(1.05)" : "scale(1)",
      }}
      onMouseDown={handleMouseDown}
      onTouchStart={handleTouchStart}
    >
      <div 
        onClick={toggleExpanded}
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          width: "30px",
          height: "30px",
          borderRadius: "50%",
          backgroundColor: isExpanded ? "rgba(255, 255, 255, 0.1)" : "transparent",
          transition: "all 0.3s ease",
          cursor: "pointer",
        }}
      >
        {!isExpanded ? (
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <polyline points="6,9 12,15 18,9"></polyline>
          </svg>
        ) : (
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <polyline points="6,15 12,9 18,15"></polyline>
          </svg>
        )}
      </div>
      
      {isExpanded && (
        <div 
          style={{ 
            display: "flex", 
            flexDirection: "column",
            alignItems: "center",
            gap: "8px",
            marginRight: "0px",
            marginBottom: "8px"
          }}
        >
          {children}
          <SettingsIcon 
            style={{
              width: "1.4em",
              height: "auto",
              cursor: "pointer",
              marginLeft: "4px"
            }}
            onClick={(e: React.MouseEvent) => {
              e.stopPropagation();
              if (onSettingsClick) {
                onSettingsClick();
              }
            }}
          />
        </div>
      )}
    </div>
  );
}